'use strict';
const Controller = require('../base');

class ContractController extends Controller {
  /* -----------------增----------------- */
  //  新增合同单申请表
  async addApplication() {
    const { ctx } = this;
    try {
      const result = await ctx.service.contract.contract.addApplication(
        ctx.request.body
      );
      this.success({ result });
    } catch (error) {
      this.error(error);
    }
  }
  // 新增付款
  async addPay() {
    const { ctx } = this;
    try {
      const result = await ctx.service.contract.contract.addPay(
        ctx.request.body
      );
      this.success({ result });
    } catch (error) {
      this.error(error);
    }
  }
  /* -----------------查----------------- */
  // 查找合同
  async getContractList() {
    const { ctx } = this;
    try {
      ctx.validate({
        name: {
          required: true,
        },
      });
      const res = await ctx.service.contract.contract.fuzzyToContract(
        ctx.query
      );
      this.success(res);
    } catch (error) {
      this.error(error);
    }
  }
  /* -----------------改----------------- */
  // 审核合同申请单
  async editApplication() {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      const result = await ctx.service.contract.contract.addContract(
        ctx.request.body
      );
      await ctx.service.contract.contract.editApplication({
        ...ctx.request.body,
        result,
      });
      transaction.commit();
      this.success({ result });
    } catch (error) {
      this.error('审核失败');
    }
  }
  // 新建合同、新建续费合同
  async detailContract() {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      const result = await ctx.service.contract.contract.detailContract(
        ctx.request.body
      );
      const { product_name, product_num, product_price } = ctx.request.body;
      if (product_name && product_num && product_price) {
        await ctx.service.contract.contract.addProduct(ctx.request.body);
      }
      transaction.commit();
      this.success(result);
    } catch (error) {
      transaction.rollback();
      this.error(error);
    }
  }
  // 审核合同
  async examineContract() {
    const { ctx } = this;
    try {
      const res = await ctx.service.contract.contract.examineContract(
        ctx.request.body
      );
      this.success(res);
    } catch (error) {
      this.error(error);
    }
  }
  /* -----------------删----------------- */
}
module.exports = ContractController;
